<template>
    <div class="url-upload-page-container">
        <!-- 1. 页面头部，包含返回按钮和标题 -->
        <div class="page-header">
            <el-button :icon="ArrowLeft" text @click="goBack" class="back-button">
                返回
            </el-button>
            <el-divider direction="vertical" />
            <h2 class="page-title">从URL上传</h2>
        </div>

        <!-- 2. 主内容区 -->
        <div class="page-content">
            <el-form :model="form" :rules="rules" ref="formRef" label-position="top" class="upload-form">

                <!-- 来源URL -->
                <el-form-item label="来源URL" prop="sourceUrl">
                    <el-input v-model="form.sourceUrl" placeholder="请输入 http://, https:// 或 rtsp:// 开头的URL" clearable
                        @change="handleUrlChange" />
                </el-form-item>

                <!-- 保存到 S3 Key -->
                <el-form-item label="保存到 (S3 Key)" prop="destinationKey">
                    <el-input v-model="form.destinationKey" placeholder="例如: a/b/my-movie.mp4">
                        <template #prepend>{{ bucketName }}/{{ displayPath }}</template>
                    </el-input>
                    <div class="form-item-description">
                        这是文件在当前存储桶内的完整路径和文件名。请确保文件名包含正确的扩展名。
                    </div>
                </el-form-item>

                <!-- 操作按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="startTransfer" :loading="isLoading" size="large">
                        {{ isLoading ? '正在创建任务...' : '开始传输' }}
                    </el-button>
                    <el-button @click="goBack" :disabled="isLoading" size="large">取消</el-button>
                </el-form-item>

            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import apiClient from '@/api';
import { useTransportStore, useSettingsStore } from '@/stores';

// --- 路由和 Store ---
const route = useRoute();
const router = useRouter();
const transportStore = useTransportStore();
const settingsStore = useSettingsStore();

// --- 响应式状态 ---
const formRef = ref(null);
const isLoading = ref(false);
const activeCollapse = ref(''); // 折叠面板默认不展开

const form = reactive({
    sourceUrl: '',
    destinationKey: '',
    credentials: {
        username: '',
        password: '',
    }
});

// --- 从路由参数获取信息 ---
const bucketName = computed(() => route.params.bucketName);
const pathArray = computed(() => (Array.isArray(route.params.path) ? route.params.path : []));
const displayPath = computed(() => (pathArray.value.length > 0 ? pathArray.value.join('/') + '/' : ''));

// --- 验证规则 ---
const rules = reactive({
    sourceUrl: [
        { required: true, message: '来源URL不能为空', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("来源URL不能为空"));
                    return;
                }
                if (value.toLowerCase().startsWith('http://') ||
                    value.toLowerCase().startsWith('https://') ||
                    value.toLowerCase().startsWith('rtsp://')) {
                    callback();
                } else {
                    callback(new Error("请输入以 http://, https://, 或 rtsp:// 开头的有效URL"));
                }
            }, trigger: ['blur', 'change']
        }
    ],
    destinationKey: [
        { required: true, message: '保存路径不能为空', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("保存路径不能为空"));
                    return;
                }
                if (value.startsWith('/')) {
                    callback(new Error("路径不能以'/'开头"));
                } else if (value.endsWith('/')) {
                    callback(new Error("路径不能以'/'结尾，必须是完整的文件名"));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ],
});


// --- 核心逻辑：处理URL变化，智能填充 ---
const handleUrlChange = (url) => {
    if (!url) return;

    // 1. 尝试从URL中解析凭据
    try {
        const urlObj = new URL(url);
        if (urlObj.username || urlObj.password) {
            ElMessageBox.confirm(
                '检测到URL中可能包含用户名和密码，是否自动为您提取并填充到“高级选项”中？这可以避免特殊字符导致的问题。',
                '智能提示',
                {
                    confirmButtonText: '提取并填充',
                    cancelButtonText: '忽略',
                    type: 'info',
                }
            ).then(() => {
                form.credentials.username = decodeURIComponent(urlObj.username);
                form.credentials.password = decodeURIComponent(urlObj.password);

                // 从主URL输入框中移除凭据，保持其干净
                urlObj.username = '';
                urlObj.password = '';
                form.sourceUrl = urlObj.toString();

                // 自动展开高级选项
                activeCollapse.value = '1';
                ElMessage.success('凭据已成功提取！');
            }).catch(() => {
                // 用户点击忽略，什么也不做
            });
        }
    } catch (e) {
        // URL格式不正确，静默失败
    }

    // 2. 自动填充目标文件名 (只在目标框为空时)
    if (!form.destinationKey) {
        autofillDestinationKey(url);
    }
}

const autofillDestinationKey = (url) => {
    try {
        // 为了能统一处理http和rtsp，我们先对URL进行标准化
        // 这个技巧可以处理没有主机名的RTSP URL等边缘情况
        const parsableUrl = url.toLowerCase().startsWith('rtsp://')
            ? 'http://placeholder.com' + url.substring(url.indexOf('/', 7)) // 用占位符主机名
            : url;

        const urlObject = new URL(parsableUrl);
        // 从路径名中提取最后一部分作为文件名
        const pathParts = urlObject.pathname.split('/').filter(p => p); // filter(p => p) 移除空字符串
        let filename = pathParts.pop() || '';

        // 解码，以处理像 %E8%81%94... 这样的编码字符
        filename = decodeURIComponent(filename);

        // 如果成功提取到了文件名，才进行填充
        if (filename) {
            // 如果是RTSP流且文件名没有扩展名，则默认添加.mp4
            if (url.toLowerCase().startsWith('rtsp://') && !filename.includes('.')) {
                form.destinationKey = `${filename}.mp4`;
            } else {
                // 对于所有其他情况（包括HTTP链接，或已有后缀的RTSP链接），直接使用提取出的文件名
                form.destinationKey = filename;
            }
        }
    } catch (e) {
        console.warn("无法从URL中自动解析文件名:", e);
        // URL格式不正确时，静默失败，不影响用户手动输入
    }
};

// --- 事件处理 ---
const goBack = () => {
    router.back();
};

const startTransfer = async () => {
    if (!formRef.value) return;
    await formRef.value.validate(async (valid) => {
        if (valid) {
            isLoading.value = true;
            try {
                // 1. 【核心】构建最终的、安全的 source_url
                let finalSourceUrl = form.sourceUrl;
                if (form.credentials.username || form.credentials.password) {
                    const urlObj = new URL(form.sourceUrl);
                    urlObj.username = form.credentials.username;
                    urlObj.password = form.credentials.password;
                    finalSourceUrl = urlObj.toString();
                }

                // 2. 构建最终的 destination_key
                const fullDestinationKey = `${displayPath.value}${form.destinationKey}`;

                // 3. 调用API
                const response = await apiClient.post(
                    `/api/v1/buckets/${bucketName.value}/upload-from-url`,
                    {
                        source_url: finalSourceUrl,
                        destination_key: fullDestinationKey,
                        chunk_size_mb: settingsStore.urlUploadChunkSize
                    }
                );

                ElMessage.success(response.data.message || '后台传输任务已创建！');

                if (response.data && response.data.task_info) {
                    transportStore.addUrlTransferTask(response.data.task_info);
                }

                // 成功后跳转回文件列表页
                goBack();

            } catch (error) {
                console.error("创建URL传输任务失败:", error);
                ElMessage.error(error.response?.data?.error || '创建任务失败，请检查URL或网络');
            } finally {
                isLoading.value = false;
            }
        }
    });
};

</script>

<style scoped>
.url-upload-page-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #f5f7fa;
}

.page-header {
    display: flex;
    align-items: center;
    padding: 0 24px;
    height: 56px;
    background-color: #fff;
    border-bottom: 1px solid #dcdfe6;
    flex-shrink: 0;
}

.back-button {
    font-size: 14px;
    padding: 0;
    color: #606266;
}

.page-title {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
    margin: 0;
}

.el-divider--vertical {
    height: 1.6em;
    margin: 0 16px;
}

.page-content {
    flex-grow: 1;
    overflow-y: auto;
    padding: 24px;
}

.upload-form {
    max-width: 800px;
    margin: 0 auto;
    background-color: #fff;
    padding: 32px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.credentials-collapse {
    margin-bottom: 22px;
    /* 与 el-form-item 的默认 margin-bottom 保持一致 */
    border-top: 1px solid var(--el-collapse-border-color);
    border-bottom: 1px solid var(--el-collapse-border-color);
}

.collapse-title {
    margin-left: 8px;
    font-weight: 500;
}

.credentials-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    background-color: #fafafa;
    padding: 20px;
    border-radius: 4px;
    border: 1px solid #e9e9eb;
}

.form-item-description {
    font-size: 12px;
    color: #909399;
    line-height: 1.5;
    margin-top: 4px;
}
</style>